package edu.drexel.info636.assignments.controllers;

import java.util.Scanner;

import org.apache.commons.lang.BooleanUtils;

/**
 * A base controller from which all controllers should inherit.
 * 
 * @author Chase Miller
 *
 */
public abstract class ControllerBase {

    protected Scanner scan;

    /**
     * Creates a new instance of this object.
     */
    public ControllerBase() {
	this.scan = new Scanner(System.in);
    }

    /**
     * Prompts the user for a boolean response.
     * 
     * @param prompt
     *            - The text to output to the user.
     * @return - True or false.
     */
    protected Boolean genericBooleanPromptAndResponse(String prompt) {
	Boolean result = null;

	while (result == null) {
	    System.out.println(prompt);
	    try {
		String resultString = this.scan.nextLine();

		result = BooleanUtils.toBoolean(resultString);

		// For some reason BooleanUtils accepts all non-yes answers as
		// false. If the user didn't enter "no" or "n," reprompt to be
		// sure.
		if (!resultString.equalsIgnoreCase("no")
			&& !resultString.equalsIgnoreCase("n")
			&& result != true) {
		    result = null;
		}
	    } catch (Throwable t) {
	    }
	}

	return result;
    }

    /**
     * Prompts the user for a new number and returns that number.
     * 
     * @return - the number gotten from the user.
     */
    protected Double getNewNumberFromUser() {
	Double newNumber = null;

	while (newNumber == null) {
	    System.out.println("Please enter a number and press enter.");

	    try {
		String resultString = this.scan.nextLine();
		newNumber = Double.parseDouble(resultString);
	    } catch (Throwable t) {
		// The user has entered an incorrect number. Give the user a
		// chance to continue or quit.
		System.out
			.println("You have entered an incorrect number.  Press r and enter to retry or anything else and enter to quit.");
		String choice = this.scan.nextLine();

		if (!choice.equalsIgnoreCase("r")) {
		    System.exit(0);
		}
	    }
	}

	return newNumber;
    }

}
